package com.tpsix.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tpsix.controller.vm.UserQueryVM;
import com.tpsix.controller.vm.UserVM;
import com.tpsix.domain.SysUserRole;
import com.tpsix.dto.DataScope;
import com.tpsix.service.SysDeptService;
import com.tpsix.service.SysUserRoleService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tpsix.mapper.SysUserMapper;
import com.tpsix.domain.SysUser;
import com.tpsix.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysDeptService sysDeptService;

    private final SysUserRoleService sysUserRoleService;

    private final PasswordEncoder passwordEncoder;

    @Override
    public List<Map<String, Object>> selectRolesAuthorities(Integer userId) {
        return baseMapper.selectRolesAuthorities(userId);
    }

    @Override
    public SysUser findUserDetailsById(int userId) {
        return baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                .select(SysUser::getId, SysUser::getUsername, SysUser::getDeptId, SysUser::getAvatar)
                .eq(SysUser::getId, userId));
    }

    @Override
    public IPage<SysUser> selectViewableUsers(Page<?> page, UserQueryVM queryVM) {
        if (Objects.nonNull(queryVM.getDeptId())) {
            // 权限范围
            queryVM.setDeptChildrenIds(sysDeptService.deptIds(queryVM.getDeptId()));
        }
        return baseMapper.selectViewableUsers(page, queryVM, DataScope.newInstance());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrUpdate(UserVM userVM) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userVM, sysUser);

        Integer userId = sysUser.getId();

        if (Objects.nonNull(sysUser.getPassword())) {
            // 密码加密
            String password = passwordEncoder.encode(sysUser.getPassword());
            sysUser.setPassword(password);
        }

        if (Objects.nonNull(userId)) {
            sysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
        }

        boolean user = saveOrUpdate(sysUser);

        List<SysUserRole> userRoles = userVM.getRoleIds()
                .stream().map(item -> {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setUserId(sysUser.getId());
                    userRole.setRoleId(item);
                    return userRole;
                }).collect(Collectors.toList());

        return user && sysUserRoleService.saveBatch(userRoles);
    }
}

